import json
import os
import cv2

img_folder_path = r''  # 图片存放文件夹
folder_path = r""  # 标注数据的文件地址
txt_folder_path = r""  # 转换后的txt标签文件存放的文件夹


# 相对坐标格式
def show_label_from_txt(img_path, txt_path):
    window_name = ('src')
    cv2.namedWindow(window_name, cv2.WINDOW_FREERATIO)
    src_img = cv2.imread(img_path)
    h, w = src_img.shape[:2]
    font = cv2.FONT_HERSHEY_SIMPLEX
    with open(temp_path, "r", encoding='utf-8') as f:
        lines = f.readlines()
    for line in lines:
        data = line.split(' ')
        label = data[1]
        x1 = int((float(data[3]) - float(data[7]) / 2) * w)
        y1 = int((float(data[5]) - float(data[9]) / 2) * h)
        x2 = int((float(data[3]) + float(data[7]) / 2) * w)
        y2 = int((float(data[5]) + float(data[9]) / 2) * h)
        p1 = (x1, y1)
        p2 = (x2, y2)
        cv2.rectangle(src_img, p1, p2, (0, 250, 0), 2)
        cv2.putText(src_img, label, p1, font, 2, (0, 255, 255), 3)
        cv2.imshow(window_name, src_img)
        cv2.waitKey(0)
    cv2.destroyAllWindows()
    return


i = 0
for txtfile in os.listdir(txt_folder_path):
    temp_path = os.path.join(txt_folder_path, txtfile)

    i += 1
    if i > 15:
        break
    # 如果是一个子目录就继续
    if os.path.isdir(temp_path):
        continue
    print("txt_path:\t", temp_path)
    img_name = txtfile.split("\\")[-1].split(".")[0] + ".jpg"
    img_path = os.path.join(img_folder_path, img_name)
    show_label_from_txt(img_path, temp_path)